package com.spsy.pay.controller.api;

import com.alibaba.fastjson2.JSON;
import com.spsy.api.pay.PayApi;
import com.spsy.common.core.domain.R;
import com.spsy.pay.domain.PaymentOrder;
import com.spsy.pay.enums.OrderStatusEnum;
import com.spsy.pay.order.WeiXinUtil;
import com.spsy.pay.service.IPaymentOrderService;
import com.spsy.vo.AddOrderVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;

@RestController
@Slf4j
public class PayApiController implements PayApi {

    @Autowired
    private IPaymentOrderService iPaymentOrderService;

    @Override
    public R createOrder(AddOrderVo addOrderVo) throws Exception {

        log.info("支付系统接受的参数 addOrderVo:{}", JSON.toJSONString(addOrderVo));

        //生产一个支付订单数据，插入到数据库
        //请求微信的下单接口，生成二维码
        log.info("请求参数 orderVo:{}", JSON.toJSONString(addOrderVo), addOrderVo.getOrderId());

        //  TODO : 参数合法性验证

        PaymentOrder paymentOrder = PaymentOrder.builder()
                .errorCode("A")
                .orderNo(UUID.randomUUID().toString())
                .notifyUrl("url")
                .errorMessage("1")
                .expireTime(new Date())
                .payAmount(new BigDecimal(12))
                .payMethod("payMethod")
                .userIp("ip")

                .notifyStatus(OrderStatusEnum.NOT_PAY.getValue())//魔法值 枚举类型

                .payTime(new Date())
                .orderStatus(1)
                .merchantOrderNo(addOrderVo.getOrderId())
                .build();

        int boo = this.iPaymentOrderService.insertPaymentOrder(paymentOrder);

        String codeUrl = WeiXinUtil.payOrder(addOrderVo.getOrderId());

        //修改二维码的数据到数据库


        log.info("codeUrl:{}", codeUrl);

        return R.ok(codeUrl);
    }

}

